<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: liguohua@clcw.com.cn  Blog:http://blog.sina.com.cn/saverneo    |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\CarResource;

use AuctionCore\Other\Address;
use AuctionCore\System\AuctionException;
use AuctionCore\CarOwner\Owner;
use AuctionCore\CarResource\CarModel;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\Cashier\Payment;

/**
 * 车辆
 * @author Eric Lee
 */
class Car
{

    private $car_id = null;

    /**
     * 构造
     * @param int $car_id 车辆id
     */
    public function __construct($car_id)
    {
        $this->car_id = $car_id;
    }

    /**
     * 车辆基本信息
     * @param string $table
     * @return mixed
     */
    public function detail($table = 'cars')
    {
        return M($table)->where("car_id='" . $this->car_id . "'")->find();
    }

    /**
     * 获取车辆基本信息，包括渠道来源
     * @return array
     * */
    public static function getDetailWithChannel($car_id)
    {
        $car_detail = M('cars')->alias('c')->field('c.*,co.comefrom,co.comefrom_url')
            ->join(" LEFT JOIN " . C('DB_PREFIX') . "car_owner as co ON c.`owner_id`=co.`owner_id`")
            ->where(array('car_id' => $car_id))->find();
        return $car_detail;
    }

    /**
     * 车辆基本信息
     * @return array
     * */
    public function get_dm_pos()
    {
        return M('car_damage')->where("car_id='" . $this->car_id . "'")->select();
    }

    /**
     * 获取车辆拍摄位置图片
     * @param int $car_id
     * @param string $pic_key
     * @return mixed
     */
    public static function get_pic_by_key($car_id, $pic_key)
    {
        $map = array();
        $map['car_id'] = $car_id;
        $map['pic_key'] = $pic_key;
        $arr = M('car_pictures')->where($map)->find();
        $arr['pic_url'] = get_content_cdnurl().$arr['pic_url'];
        return $arr;
    }

    /**
     * 获取车辆图片信息
     * @param string $cond 条件
     * @return array
     * */
    public function get_pics($table = 'car_pictures', $cond = '')
    {
        return M($table)->where($cond)->select();
    }

    /**
     * 新增车源
     * @param    array $data 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array()
     * @return   bool
     */
    public static function create($data)
    {
        //事务处理
        M()->startTrans();

        //-----增加车辆基本信息
        $brand = M('car_brand')->where("brand_id='" . $data['brand_id'] . "'")->getField('name');
        $series = M('car_series')->where("series_id='" . $data['series_id'] . "'")->getField('name');
        $model = M('car_model')->where("model_id='" . $data['model_id'] . "'")->getField('name');
        $model = $brand . ' ' . $series . ' ' . $model;

        $cars_data = array();
        foreach (M('cars')->getDbFields() as $col) {
            if ($col == 'car_id')
                continue;
            if (!in_array($col, array_keys($data)))
                continue;
            $cars_data[$col] = $data[$col];
        }
        $cars_data['mbrand_id'] = M('car_brand')->where("brand_id='" . $data['brand_id'] . "'")->getField('mbrand_id');

        //加锁解决并发问题，防此生成相同编号
        $redis = new \AuctionCore\Common\PhpRedis(0);
        $max_car_id = M('cars')->max('car_id');

        $keyArr = [
            'max_car_id' => $max_car_id,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100015',$keyArr);

        $lock = $redis->lock($keyName);
        //$lock = $redis->lock('lock_report_car_id_' . $max_car_id);
        if ($lock) {
            $cars_data['car_no'] = gen_car_no();
            $cars_data['car_status'] = 1;//待审核
            if (!empty($data['protocol_pic'])) {
                $cars_data['is_proto_uploaded'] = 1;//协议已上传
            }
            $cars_data['posttime'] = date('Y-m-d H:i:s');
            \Think\Log::record(date('Y-m-d H:i:s') . '开始插入车辆基本信息');
            $ret = M('cars')->add($cars_data);
            $redis->unlock($keyName);
            //$redis->unlock('lock_report_car_id_' . $max_car_id);
        } else {
            \Think\Log::record(date('Y-m-d H:i:s') . '并发退回请求(车型' . $model . ',车主:' . $data['seller_name'] . ',手机:' . $data['phone'] . ',车架号：' . $data['vin'] . ')');
            return false;
        }

        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息添加失败(车型' . $model . ',车主:' . $data['seller_name'] . ',手机:' . $data['phone'] . ',车架号：' . $data['vin'] . ')');
            M()->rollback();
            return false;
        }
        $car_id = M('cars')->getLastInsID();

        //-----车辆手续
        \Think\Log::record(date('Y-m-d H:i:s') . '开始插入手续信息.' . $car_id . ')');
        $ret = self::car_procedure($data, $car_id);
        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息添加失败(添加手续信息失败,car_id:' . $car_id . ')');
            M()->rollback();
            return false;
        }

        //-----车辆配置信息
        \Think\Log::record(date('Y-m-d H:i:s') . '开始插入配置信息.' . $car_id . ')');
        $ret = self::car_config($data, $car_id);
        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息添加失败(添加配置信息失败,car_id:' . $car_id . ')');
            M()->rollback();
            return false;
        }

        //-----基本图片表（15张图片)
        \Think\Log::record(date('Y-m-d H:i:s') . '开始插入基本图片.' . $car_id . ')');
        $ret = self::car_pictures($data, $car_id);
        if (!$ret) {
            M()->rollback();
            return false;
        }

        //-----修复历史表
        \Think\Log::record(date('Y-m-d H:i:s') . '开始插入修复历史.' . $car_id . ')');
        $ret = self::car_repair_history($data, $car_id);
        if (!$ret) {
            M()->rollback();
            return false;
        }

        //-----损伤表
        \Think\Log::record(date('Y-m-d H:i:s') . '开始插入损伤信息.' . $car_id . ')');
        $ret = self::car_damage($data, $car_id);
        if (!$ret) {
            M()->rollback();
            return false;
        }

        //-----工况表
        $ret = self::car_perform($data, $car_id);
        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息添加失败(添加工况及附件信息失败,car_id:' . $car_id . ')');
            M()->rollback();
            return false;
        }

        //-----更新车主表
        $owner_id = self::car_owner($data, $car_id, $model);
        if (!$owner_id) {
            M()->rollback();
            return false;
        }

        \Think\Log::record(date('Y-m-d H:i:s') . '车源信息添加成功！,car_id:' . $car_id . ')');
        //事务提交
        M()->commit();
        $ret = array();
        $ret['car_id'] = $car_id;
        $ret['car_no'] = $cars_data['car_no'];
        $ret['owner_id'] = $owner_id;
        return $ret;
    }

    /**
     * 增加|更新手续信息数据
     * @param    array $data 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array()
     * @param    int $car_id 车辆ID
     * @param    string $act_type 操作类型(insert|update)
     * @return   bool
     */
    private function car_procedure($data, $car_id, $act_type = 'insert')
    {
        $procedure_data = array();
        foreach (M('car_procedure')->getDbFields() as $col) {
            if ($col == 'pro_id')
                continue;
            if (!in_array($col, array_keys($data)))
                continue;
            $procedure_data[$col] = $data[$col];
        }
        if ($act_type == 'insert') {
            $procedure_data['car_id'] = $car_id;
            return M('car_procedure')->add($procedure_data);
        } else {
            M('car_procedure')->where("car_id='" . $car_id . "'")->save($procedure_data);
            return true;
        }
    }

    /**
     * 增加|更新车辆配置数据
     * @param    array $data 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array()
     * @param    int $car_id 车辆ID
     * @param    string $act_type 操作类型(insert|update)
     * @return   bool
     */
    private function car_config($data, $car_id, $act_type = 'insert')
    {
        $car_config_data = array();
        foreach (M('car_config')->getDbFields() as $col) {
            if ($col == 'conf_id')
                continue;
            if (!in_array($col, array_keys($data)))
                continue;
            $car_config_data[$col] = $data[$col];
        }
        if ($act_type == 'insert') {
            $car_config_data['car_id'] = $car_id;
            return M('car_config')->add($car_config_data);
        } else {
            M('car_config')->where("car_id='" . $car_id . "'")->save($car_config_data);
            return true;
        }
    }

    /**
     * 增加|更新基本图片数据
     * @param    array $data 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array()
     * @param    int $car_id 车辆ID
     * @param    string $act_type 操作类型(insert|update)
     * @return   bool
     */
    private function car_pictures($data, $car_id, $act_type = 'insert')
    {
        $car_pictures_data = array();
        if ($act_type == 'insert') {
            $msg = "添加";
        } else {
            $ret = M('car_pictures')->where("car_id='" . $car_id . "'")->delete();
            if (!$ret) {
                \Think\Log::record(date('Y-m-d H:i:s') . '车源信息更新失败(删除基本图片失败,car_id:' . $car_id . ')');
                return false;
            }
            $msg = "更新";
        }
        foreach (C('BASE_PIC_POS') as $key => $desc) {
            if (empty($data[$key]))
                continue;
            $car_pictures_data['car_id'] = $car_id;
            $car_pictures_data['pic_key'] = $key;
            $car_pictures_data['pic_url'] = $data[$key];
            $car_pictures_data['pic_desc'] = $desc;
            $ret = M('car_pictures')->add($car_pictures_data);
            if (!$ret) {
                \Think\Log::record(date('Y-m-d H:i:s') . '车源信息' . $msg . '失败(' . $msg . '基本图片失败,图片:' . $data[$key] . ',car_id:' . $car_id . ')');
                return false;
            }
        }
        return true;
    }

    /**
     * 增加|更新修复历史数据
     * @param    array $data 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array()
     * @param    int $car_id 车辆ID
     * @param    string $act_type 操作类型(insert|update)
     * @return   bool
     */
    private function car_repair_history($data, $car_id, $act_type = 'insert')
    {
        $car_repair_history_data = array();
        if ($act_type == 'insert') {
            $msg = "添加";
        } else {
            $ret = M('car_repair_history')->where("car_id='" . $car_id . "'")->delete();
            if (!$ret) {
                \Think\Log::record(date('Y-m-d H:i:s') . '车源信息更新失败(删除修改历史信息失败,car_id:' . $car_id . ')');
                return false;
            }
            $msg = "更新";
        }
        foreach (M('car_repair_history')->getDbFields() as $col) {
            if ($col == 'repair_id')
                continue;
            if (!in_array($col, array_keys($data)))
                continue;
            $car_repair_history_data[$col] = $data[$col];
        }
        $car_repair_history_data['car_id'] = $car_id;
        $ret = M('car_repair_history')->add($car_repair_history_data);
        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息' . $msg . '失败(' . $msg . '修复历史信息失败,car_id:' . $car_id . ')');
            return false;
        }
        return true;
    }

    /**
     * 增加|更新损伤信息数据
     * @param    array $data 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array())
     * @param    int $car_id 车辆ID
     * @param    string $act_type 操作类型(insert|update)
     * @return   bool
     */
    private function car_damage($data, $car_id, $act_type = 'insert')
    {
        //
        if ($act_type == 'update') {
            M('car_damage_pics')->where("dm_id in(SELECT dm_id FROM " . C('DB_PREFIX') . "car_damage WHERE car_id='" . $car_id . "')")->delete();
            M('car_damage')->where("car_id='" . $car_id . "'")->delete();
        }
        foreach ($data['damage_info'] as $val) {
            $car_damage_data = array();
            $car_damage_data['position'] = $val['position'];
            $car_damage_data['visible_type'] = $val['visible_type'];
            $car_damage_data['dm_degree'] = $val['dm_degree'];
            $car_damage_data['describe'] = $val['describe'];
            $car_damage_data['cus_pos_name'] = $val['cus_pos_name'];
            $ret = true;
            $msg = '';
            $car_damage_data['car_id'] = $car_id;
            $dm_id = M('car_damage')->add($car_damage_data);
            if (!$dm_id) {
                if ($act_type == 'insert') {
                    $msg = date('Y-m-d H:i:s') . '车源信息添加失败(添加损伤信息失败,损伤位置编号:' . $val['position'] . ',car_id:' . $car_id . ')';
                } else {
                    $msg = date('Y-m-d H:i:s') . '车源信息更新失败(添加损伤信息失败,损伤位置编号:' . $val['position'] . ',car_id:' . $car_id . ')';
                }
                $ret = false;
            }
            if (!$ret) {
                \Think\Log::record($msg);
                return false;
            }
            //-----损伤图片表
            $car_damage_pics_data = array();
            foreach ($val['urls'] as $url) {
                $car_damage_pics_data['url'] = $url;
                $car_damage_pics_data['dm_id'] = $dm_id;
                $ret = M('car_damage_pics')->add($car_damage_pics_data);
                if (!$ret) {
                    \Think\Log::record(date('Y-m-d H:i:s') . '车源信息更新失败(添加损伤图片失败,损伤位置编号:' . $val['position'] . ',car_id:' . $car_id . ')');
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 增加|更新工况信息
     * @param    array $data 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array()
     * @param    int $car_id 车辆ID
     * @param    string $act_type 操作类型(insert|update)
     * @return   bool
     */
    private function car_perform($data, $car_id, $act_type = 'insert')
    {
        $car_perform_data = array();
        foreach (M('car_perform')->getDbFields() as $col) {
            if ($col == 'ws_id')
                continue;
            if (!in_array($col, array_keys($data)))
                continue;
            $car_perform_data[$col] = $data[$col];
        }
        if ($act_type == 'insert') {
            $car_perform_data['car_id'] = $car_id;
            return M('car_perform')->add($car_perform_data);
        } else {
            M('car_perform')->where("car_id='" . $car_id . "'")->save($car_perform_data);
            return true;
        }
    }

    /**
     * 增加|更新车主信息
     * @param    array $data 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array()
     * @param    int $car_id 车辆ID
     * @param    string $model 品牌车系车型
     * @return   bool
     */
    private function car_owner($data, $car_id, $model)
    {

        //车主信息
        foreach (M('car_owner')->getDbFields() as $col) {
            if ($col == 'owner_id')
                continue;
            if (!in_array($col, array_keys($data)))
                continue;
            $car_owner_data[$col] = $data[$col];
        }
        $car_owner_data['business_status'] = '5'; //业务状态 检测通过

        $car_owner_data['car_model'] = $model;
        $car_owner_data['mileage'] = $data['pointer_mileage'];
        $car_owner_data['first_reg_city'] = $data['reg_city'];
        $car_owner_data['modify_time'] = date('Y-m-d H:i:s');
        $owner_id = $data['owner_id'];
        if ($owner_id) {//修改车源信息,只需要更新下车主信息
            //TODO:一个车主对多个车源时，这里是有数据丢失问题（前一辆车的车主信息数据会被替换）(前期解决方案：去掉手机限制，每增加一辆车重新插入一条车主记录)
            $Owner = new Owner($data['owner_id']);
            $Owner->update($car_owner_data);
        } else {//
            //$owner_id = M('car_owner')->where("phone='".$data['phone']."'")->getField('owner_id');
            //if($owner_id){//有线索记录,需要更新车主信息
            //    $Owner = new Owner($owner_id);
            //    $Owner->update($car_owner_data);
            //}else{//没有线索记录，需要新增车主信息,同时修改车源表里的owner_id
            $car_owner_data['is_self_upload'] = 1;
            $car_owner_data['checker_id'] = $data['emp_id'];
            $car_owner_data['posttime'] = date('Y-m-d H:i:s');
            $msg = '';
            try {
                Owner::create($car_owner_data);
            } catch (\Exception $e) {
                \Think\Log::record(date('Y-m-d H:i:s') . '车源信息添加失败(添加车主信息失败,' . $e->getMessage() . ',car_id:' . $car_id . ')');
                return false;
            }
            $owner_id = M('car_owner')->getLastInsID();
            //}
        }
        //更新车源
        $cars = array();
        $cars['owner_id'] = $owner_id;
        $cars['mbrand_id'] = M('car_brand')->where("brand_id='" . $data['brand_id'] . "'")->getField('mbrand_id');
        M('cars')->where("car_id='" . $car_id . "'")->save($cars);
        return $owner_id;
    }

    /**
     * 更新车源
     * @param $data array 更新数据
     * @return Boolean
     * */
    public function update($data, $table = 'cars')
    {
        $result = M($table)->where("car_id='" . $this->car_id . "'")->save($data);
        // echo M()->getLastSql();
        return $result;
    }

    /**
     * 更新车辆信息
     * @param $data
     * @return bool
     */
    public function updateCar($data)
    {
        if (empty($data) || $this->car_id < 1) return false;
        $data['modify_time'] = date('Y-m-d H:i:s');
        return M("cars")->where(["car_id" => $this->car_id])->save($data);
    }

    /**
     * 修改车源
     * @param    int $car_id 车源信息 数据结构 $data = array('seller_name'=>'xxxx',....'damage_info'=>array('position'=>'1',...'urls'=>array()
     * @return   bool
     */
    public static function edit_car($data)
    {

        $car_id = $data['car_id'];
        if (!$car_id) {
            return false;
        }
        $c = M('cars')->where("car_id='" . $car_id . "'")->find();
        if (!$c) {
            return false;
        }
        //事务处理
        M()->startTrans();

        //-----获取车辆基本信息
        $brand = M('car_brand')->where("brand_id='" . $data['brand_id'] . "'")->getField('name');
        $series = M('car_series')->where("series_id='" . $data['series_id'] . "'")->getField('name');
        $model = M('car_model')->where("model_id='" . $data['model_id'] . "'")->getField('name');
        $model = $brand . ' ' . $series . ' ' . $model;

        $cars_data = array();
        foreach (M('cars')->getDbFields() as $col) {
            if ($col == 'car_id')
                continue;
            if (!in_array($col, array_keys($data)))
                continue;
            $cars_data[$col] = $data[$col];
        }
        $cars_data['car_no'] = $c['car_no'];
        $cars_data['car_status'] = 1;//待审核

        if ($c['is_proto_uploaded'] <= 0) {
            if (!empty($data['protocol_pic'])) {
                $cars_data['is_proto_uploaded'] = 1;//协议已上传
            }
        }

        $cars_data['modify_time'] = date('Y-m-d H:i:s');

        $ret = M('cars')->where("car_id='" . $data['car_id'] . "'")->save($cars_data);
        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息更新失败(car_id:' . $car_id . ")\n");
            M()->rollback();
            return false;
        }

        //-----车辆手续
        $ret = self::car_procedure($data, $car_id, 'update');
        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息更新失败(更新手续信息失败,car_id:' . $car_id . ")\n");
            M()->rollback();
            return false;
        }

        //-----车辆配置信息
        $ret = self::car_config($data, $car_id, 'update');
        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息更新失败(更新配置信息失败,car_id:' . $car_id . ")\n");
            M()->rollback();
            return false;
        }

        //-----基本图片表（15张图片)
        $ret = self::car_pictures($data, $car_id, 'update');
        if (!$ret) {
            M()->rollback();
            return false;
        }

        //-----修复历史表
        $ret = self::car_repair_history($data, $car_id, 'update');
        if (!$ret) {
            M()->rollback();
            return false;
        }

        //-----损伤表
        $ret = self::car_damage($data, $car_id, 'update');
        if (!$ret) {
            M()->rollback();
            return false;
        }

        //-----工况表
        $ret = self::car_perform($data, $car_id, 'update');
        if (!$ret) {
            \Think\Log::record(date('Y-m-d H:i:s') . '车源信息更新失败(更新工况及附件信息失败,car_id:' . $car_id . ')');
            M()->rollback();
            return false;
        }

        //-----更新车主表
        $owner_id = self::car_owner($data, $car_id, $model);
        if (!$owner_id) {
            M()->rollback();
            return false;
        }

        \Think\Log::record(date('Y-m-d H:i:s') . '车源信息更新成功！,car_id:' . $car_id . ')');

        //事务提交
        M()->commit();
        //返回
        $ret = array();
        $ret['car_id'] = $car_id;
        $ret['car_no'] = $cars_data['car_no'];
        $ret['owner_id'] = $owner_id;
        return $ret;
    }

    /**
     * 评估报告
     * @return   array
     */
    public function report()
    {
        $data = array();

        //车辆基本信息
        $data['car_base'] = M('cars')->find($this->car_id);
        //车辆手续信息
        $data['procedure'] = M('car_procedure')->where("car_id='" . $this->car_id . "'")->find();
        //车辆配置信息
        $data['config'] = M('car_config')->where("car_id='" . $this->car_id . "'")->find();
        //车辆基本图片
        $data['pictures'] = M('car_pictures')->where("car_id='" . $this->car_id . "'")->select();
        foreach($data['pictures'] as $k => $v){
            $data['pictures'][$k]['pic_url'] = get_content_cdnurl().$v['pic_url'];
        }
        //车辆修复历史
        $data['repair_history'] = M('car_repair_history')->where("car_id='" . $this->car_id . "'")->find();
        //车辆损伤信息
        $data['damage'] = M('car_damage')->where("car_id='" . $this->car_id . "'")->select();
        //车辆损伤图片信息
        foreach ($data['damage'] as $key => $value) {
            $data['damage'][$key]['urls'][] = M('car_damage_pics')->where("dm_id='" . $value['dm_id'] . "'")->select();
        }
        //车辆工况信息
        $data['perform'] = M('car_perform')->where("car_id='" . $this->car_id . "'")->find();
        //车主信息
//         $data['owner'] = M('car_owner')->find($data['car_base']['owner_id']);

        $data['owner'] = M('car_owner a')
            ->join(C('DB_PREFIX') . 'come_from b ON a.comefrom=b.from_id')
            ->field('a.*,b.pid')
            ->find($data['car_base']['owner_id']);

        return $data;
    }

    /**
     * 车源审核通过
     * @param    string $remark 审核备注信息
     * @return   void
     */
    public function auditing_sucess($remark)
    {
        $data = array();
        $data['status'] = '4';
        $data['remark'] = $remark;
        M('cars')->where("car_id='" . $this->car_id . "'")->save($data);
        //\Think\Log::record('');
    }

    /**
     * 车源审核失败
     * @param    string $remark 审核备注信息
     * @return   void
     */
    public function auditing_faild($remark)
    {
        $data = array();
        $data['status'] = '3';
        $data['remark'] = $remark;
        M('cars')->where("car_id='" . $this->car_id . "'")->save($data);
        //\Think\Log::record('');
    }

    /**
     * 车源审核驳回
     * @param    string $remark 审核备注信息
     * @return   void
     */
    public function auditing_reject($remark)
    {
        $data = array();
        $data['status'] = '3';
        $data['remark'] = $remark;
        M('cars')->where("car_id='" . $this->car_id . "'")->save($data);
        //\Think\Log::record('');
    }

    /**
     * 生成拍单，返回新的拍单id
     * @param    array $order 拍单信息
     * @return   int
     */
    public function create_order($order)
    {

        if (empty($this->car_id)) {
            AuctionException::make_throw('600001');
        }
        if (empty($order['scene_id'])) {
            AuctionException::make_throw('700010');
        }
        if (empty($order['est_elapsed_time'])) {
            AuctionException::make_throw('700026');
        }
        if (empty($order['bid_start_price'])) {
            AuctionException::make_throw('700013');
        }
        if (empty($order['transfer_fee'])) {
            AuctionException::make_throw('700015');
        }
        //优先级
        $rank = M('order')->where(['scene_id' => $order['scene_id']])->max('rank');
        $order['rank'] = $rank + 1;
        //检查该车是否已有拍单，且拍单状态不为流拍和失败
        $where = [];
        $where['car_id'] = $this->car_id;
        $where['status'] = ['neq', 12];
        $check = M('order')->field("order_id,status,fail_type")->where($where)->order("order_id DESC")->find();

        if (!empty($check)) {
            if ($check['status'] != 2) {
                AuctionException::make_throw('500061');
            } else {
                $order['status'] = 1;
                $order['last_time'] = date('Y-m-d H:i:s');
                $res = M('order')->where(['order_id' => $check['order_id']])->save($order);
                if (!$res) {
                    AuctionException::make_throw('700043');
                }
                $order_id = $check['order_id'];
                $msg = "重上驳回的拍单:order_id:" . $check['order_id'];
            }
        } else {  //正常上班
            //加锁解决并发问题，防此生成相同编号
            $redis = new \AuctionCore\Common\PhpRedis(0);
            $max_order_id = M('order')->max('order_id');
            $keyArr = [
                'max_order_id' => $max_order_id,
            ];
            $keyName = getRedisKeyByCode('REDIS_KEY','100016',$keyArr);

            $lock = $redis->lock($keyName);
            //$lock = $redis->lock('lock_au_order_id_' . $max_order_id);
            if (!$lock) {
                AuctionException::make_throw('100066');
            }
            $order['order_no'] = gen_order_no();
            $order['create_time'] = date('Y-m-d H:i:s');
            $order_id = M('order')->add($order);
            //解锁
            $redis->unlock($keyName);
            //$redis->unlock('lock_au_order_id_' . $max_order_id);

            if (!$order_id) {
                AuctionException::make_throw('100066');
            }
            $msg = "生成新的拍单：order_id:" . $order_id;
            //更改车源状态为5(拍卖中)
            $car = new Car($this->car_id);
            $car->update(array('car_status' => '5'));
        }
        //操作日志
        //操作日志
        $log = array(
            'car_id' => $this->car_id,
            'order_id' => $order_id,
            'emp_id' => $order['emp_id'],
            'action' => $msg
        );
        \AuctionCore\System\SystemLog::add($log);
        return $order_id;
    }

    /*
     * 必填项
     * @param string $key 键名
     * @return Array
     * */

    function must_column($key)
    {
        $cols = array();
        //TODO:需要检测所有必填字段且抛出异常
        //基本信息表
        $cols[''] = array('code' => '', 'msg' => '');
        //手续表
        $cols[''] = array('code' => '', 'msg' => '');
        //配置表
        $cols[''] = array('code' => '', 'msg' => '');
        //基本图片表
        $cols[''] = array('code' => '', 'msg' => '');
        //修复历史表
        $cols[''] = array('code' => '', 'msg' => '');
        //损伤表
        $cols[''] = array('code' => '', 'msg' => '');
        //工况表
        $cols[''] = array('code' => '', 'msg' => '');
        //车主表
        $cols[''] = array('code' => '', 'msg' => '');
    }

    /**
     *
     */
    public static function key_to_carid($keyword)
    {
        $res = M('cars')->alias('c')->field('car_id')
            ->join(C('DB_PREFIX') . "car_brand cb ON c.brand_id=cb.brand_id")
            ->join(C('DB_PREFIX') . "car_series cs ON c.series_id=cs.series_id")
            ->join(C('DB_PREFIX') . "car_model cm ON c.model_id=cm.model_id")
            ->where("cb.name like '%" . $keyword . "%' OR cs.name like '%" . $keyword . "%' OR cm.name like '%" . $keyword . "%'")
            ->select();
        $car_ids = array();
        foreach ($res as $k => $v) {
            $car_ids[] = $v['car_id'];
        }
        return $car_ids;
    }

    /**
     * 根据线索ID，查询车源信息
     * */
    public static function get_car_by_owner_id($owner_id)
    {
        return M('cars')->where("owner_id='" . $owner_id . "'")->find();
    }

    /**
     * 根据线索ID，查询车源信息
     * */
    public static function get_car_by_vin($vin)
    {
        $ret = array();
        $res = M('cars')->where("vin='" . $vin . "' AND (" . time() . "-UNIX_TIMESTAMP(posttime))<=3600*24*4")->order('posttime DESC')->find();
        if ($res) {
            $ret['car_id'] = $res['car_id'];
            $ret['car_no'] = $res['car_no'];
            $ret['owner_id'] = $res['owner_id'];
        }
        return $ret;
    }

    /**
     * 通过车辆编号查询车辆信息
     * @param unknown $car_no
     * @return boolean|\Think\mixed
     */
    public static function get_car_by_car_no($car_no)
    {
        if (empty($car_no)) {
            return false;
        }
        return M('cars')->where("car_no='" . $car_no . "'")->find();
    }

    /**
     * 根据车源编号获取车辆信息
     * @param $sno
     * @return bool|mixed
     */
    public static function getCarBySno($sno)
    {
        if(empty($sno)) return false;
        return M("cars")->where(['sno'=>$sno])->find();
    }

    /**
     * 计算顺序单开拍时间
     * @param $scene_id
     * @return mixed
     */
    public function get_bidding_start_time($scene_id)
    {
        $res = M('order_scene')->field("starttime")->where("scene_id='" . $scene_id . "'")->find();
        $time_offset = strtotime($res['starttime']);

        $res1 = M('order')->field("est_elapsed_time,rank")->where("scene_id='" . $scene_id . "' and rank>0 and is_timing_order=0 and status not in(2,6,12)")
            ->order("rank")->select();
        $time_offset1 = 0;
        foreach ($res1 as $k => $v) {
            $time_offset1 += $v['est_elapsed_time'];
        }
        return date('Y-m-d H:i:s', $time_offset + $time_offset1);
    }

    /**
     * 判断定时单开拍时间是否合法(定时单必须大于等于场开始时间)
     * @param $scene_id
     * @param $bidding_start_time
     * @return bool
     * @author Eric Lee
     */
    public function check_bidding_start_time($scene_id, $bidding_start_time)
    {
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $scene_detail = $scene->detail($scene_id);
        if ($bidding_start_time < $scene_detail['starttime'] || date('Y-m-d', strtotime($bidding_start_time)) != date('Y-m-d', strtotime($scene_detail['starttime']))) {
            return false;
        }
        return true;
    }

    public function get_car_name()
    {
        $car = $this->detail();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($car['brand_id'], 'brand');
        $model = $cm->get_model_by_id($car['model_id']);
        $series = $cm->get_model_by_id($car['series_id'], 'series');
        $car_name = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'] . ' ' . $car['car_cc'] . ($car['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car['gearbox']);
        //$series['name'] . ' ' . $val['car_cc'] . ($val['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $val['gearbox']);
        return $car_name;
    }

    /**
     * 添加记录车辆跟踪信息
     */
    /* public static function add_car_trace_log($car_action_data)
     {
         $car_trace = M('car_trace_log');
         $createtime = date("Y-m-d H:i:s", time());
         $car_trace_log['owner_id'] = $car_action_data['owner_id'];
         $car_trace_log['car_id'] = $car_action_data['car_id'];
         $car_trace_log['action_log'] = $createtime . "/t" . $car_action_data['car_trace_msg'] . '/t' . $car_action_data['employee'] . '/n/t';
         $car_trace_log['createtime'] = $createtime;
         $ok = $car_trace->add($car_trace_log);
         return $ok;
     }*/
    /* public function get_car_trace_log(){
         $car_trace_log = M('car_trace_log')->field('action_log')->where(array('car_id' => $car_id))->find();
         $action_log = $car_trace_log['action_log'];
         $action_log_arr = array_filter(explode("/n/t", $action_log));
         $car_action_log = array();
         foreach ($action_log_arr as $k => $v) {
             $car_action_log[$k] = explode('/t', $v);
         }
 //        $car_action_log = $this->key_arr_sort($car_action_log, '0');
         return $car_action_log;
     }*/
    /**
     * 添加记录车辆跟踪信息
     * @param int $car_id
     * @param array $car_action_data
     * @return int
     */
    public static function add_car_trace_log($car_id, $car_action_data)
    {
        $carInfo = M('cars')->where(['car_id' => $car_id])->find();
        $sid = $carInfo['sid'];
        $car_trace = M('car_trace_log_list');
        $owner_id = M('cars')->where(['car_id' => $car_id])->getField('owner_id');
        $car_trace_log['owner_id'] = $owner_id;
        $car_trace_log['car_id'] = $car_id;
        $emp_id = $car_action_data['emp_id'];
        $employee = \AuctionCore\Account\Back\Employee::user_info_id($emp_id);
        if (!empty($employee)) {
            $emp_name = $employee['real_name'];
        } else {
            $emp_name = '--';
        }
        $car_trace_log['sid'] = $sid;
        $car_trace_log['emp_id'] = $emp_id;
        $car_trace_log['emp_name'] = $emp_name;
        $car_trace_log['action_no'] = array_keys(C('CAR_ACTION_NAME'), $car_action_data['action_name'])[0];
        $car_trace_log['action_name'] = $car_action_data['action_name'];
        $car_trace_log['createtime'] = microtime_time();
        $ok = $car_trace->add($car_trace_log);
        return $ok;
    }

    /**
     * 获取车辆日志
     * @param $car_id
     * @return $list
     */
    public static function get_car_trace_log_list($car_id)
    {
        if ($car_id < 1) {
            return false;
        }
        $carInfo = M('cars')->where(['car_id' => $car_id])->find();
        $sid = $carInfo['sid'];

        $car_trace = M('car_trace_log_list');
        $cols = 'emp_name,action_name,createtime';
        $list = $car_trace->field($cols)->where(['sid' => $sid])->order('id DESC')->select(); //根据sid 获取操作日志
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['createtime'] = date('Y-m-d H:i:s', ceil($v['createtime'] / 1000));
                if (empty($v['emp_name'])) {
                    $list[$k]['emp_name'] = '--';
                }
            }
        }
        return $list;
    }

    /**
     * 添加更新记录车辆跟踪信息
     */
    public static function save_car_trace_log($car_id, $car_action_data)
    {
        $car_trace = M('car_trace_log');
        $action_log = $car_action_data['createtime'] . "/t" . $car_action_data['car_trace_msg'] . '/t' . $car_action_data['employee'] . '/n/t';
        $car_trace_log['action_log'] = array('exp', "CONCAT(`action_log`,'$action_log')");
        $ok = $car_trace->where(array('car_id' => $car_id))->save($car_trace_log);
        return $ok;
    }

    /**
     * 获取车辆跟踪日志信息
     * @param  int $car_id
     * @return array
     */
    public static function get_car_trace_log($car_id)
    {
        if ($car_id < 1) return false;
        $condition['car_id'] = ['eq', $car_id];
        $cols = 'id,emp_name,action_no,action_name,createtime';
        $order = 'id DESC';
        return M("car_trace_log_list")->field($cols)->where($condition)->order($order)->select();
    }


    /**
     *  根据车源号和操作编号，得到相应的操作信息
     *
     * @param $car_id 车源编号
     * @param $action_no 操作编号
     * @return bool
     */
    public static function get_car_trace_log_by_action_no($car_id, $action_no)
    {
        if ($car_id < 1) return false;
        $condition['car_id'] = ['eq', $car_id];
        $condition['action_no'] = ['eq', $action_no];

        $cols = 'id,emp_name,action_no,action_name,createtime';
        $order = 'id DESC';
        return M("car_trace_log_list")->field($cols)->where($condition)->order($order)->find();
    }


    /**
     * 通过车牌号查询车辆
     * @param $prefix
     * @param $suffix
     * @return mixed
     */
    public static function getCarByPlateNo($prefix, $suffix)
    {
        $map = [
            'plate_prefix' => $prefix,
            'plate_suffix' => $suffix,
        ];

        return M("cars")->where($map)->find();
    }

    /**
     * 车辆基本信息
     * @return mixed
     */
    public function baseInfo()
    {
        $car = $this->detail();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($car['brand_id'], 'brand');
        $model = $cm->get_model_by_id($car['model_id']);
        $series = $cm->get_model_by_id($car['series_id'], 'series');
        $car['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'] . ' ' . $car['car_cc'] . ($car['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car['gearbox']);
        $car['emission'] = C('EMISSION.' . $car['emission']);
        $addr = new Address();
        $car['location_area_str'] = $addr->get_name_by_code($car['location_area']);
        $car['reg_city'] = $addr->get_name_by_code($car['reg_city']);
        $car['transfer_limit_str'] = C('TRANSFER_LIMIT.' . $car['transfer_limit']);
        $car['car_color'] = C('CAR_COLOR.' . $car['car_color']);
        $car['plate_no'] = C('PLATE_PREFIX.' . $car['plate_prefix']) . $car['plate_suffix'];
        $car['pointer_mileage'] = round($car['pointer_mileage'] / 10000, 2);
        return $car;
    }

    //根据车辆id获取拍单id
    public function get_orderid_by_carid($car_id)
    {
        $map = array();
        $map['car_id'] = array('eq', $car_id);
        $order_info = M('order')->where($map)->order('order_id desc')->find();
        return $order_info['order_id'];
    }

    /**
     * 根据车源编号，得到相关的报告编号
     *
     * @param int $sid 车源编号
     * @return mixed
     */
    public function getCarIdsBySid($sid)
    {
        $map = array();
        $map['sid'] = array('eq', $sid);
        $carIds = M('cars')->field('car_id')->where($map)->order('car_id desc')->select();
        return $carIds;
    }

    /**
     * 得到首付款信息
     *
     * @param int $sid 车源编号
     * @return array|mixed
     */
    public static function getFirstPaymentBySid($sid)
    {
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        if (empty($purchaseOrderData)) {
            return [];
        }
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号
        $paymentRelation = $purchaseOrderObj->getPaymentAndPurchaseOrderRelation($purchaseOrderId, [1, 2]);
        $paymentId = $paymentRelation['payment_id'];

        $paymentObj = new Payment($paymentId);
        $paymentData = $paymentObj->getInfo();
        if ($paymentData['status'] != 1) { //如果不是已付款，就让付款金额变为0
            $paymentData['amount'] = 0;
        }
        return $paymentData;
    }


    /**
     * 根据sid 得到有效的car_id
     *
     * @param int $sid 车辆编号
     * @return mixed
     */
    public static function getValidCarIdBySid($sid)
    {
        $map = array();
        $map['sid'] = array('eq', $sid);
        $carId = M('cars')->field('car_id')->where($map)->order('car_id desc')->select();
        return $carId;
    }

    /**
     * 根据车源编号查找所有的报告ID
     * @param $sno
     * @return array
     */
    public static function getAllCarIdByCarSourceNu($sno)
    {
        $carIds = [];
        $map = [];
        $map['sno'] = trim($sno);
        $cars = M("cars")->field('car_id')->where($map)->select();
        foreach ($cars as $car){
            $carIds[] = $car['car_id'];
        }
        return $carIds;
    }

    /**
     * 根据sid获取所有的car_id
     * @param $sid
     * @return array
     */
    public static function getAllCarIdBySid($sid)
    {
        $carIds = [];
        $map = [];
        $map['sid'] = intval($sid);
        $cars = M("cars")->field('car_id')->where($map)->select();
        foreach ($cars as $car){
            $carIds[] = $car['car_id'];
        }
        return $carIds;
    }

    /**
     * 根据sid更新车辆状态
     * @param $sid
     * @param $pay_status
     * @return bool
     */
    public static function updatePayStatusBySid($sid,$pay_status)
    {
        $map = ['sid' => $sid];
        $data = ["pay_status"=>$pay_status];
        return M("cars")->where($map)->save($data);
    }
    //给图片增加前缀
    public function prefix_url($data){
        if(!empty($data['protocol_pic'])){
            $data['protocol_pic'] = get_content_cdnurl().$data['protocol_pic'];
        }
        if(!empty($data['travel_license_pic'])){
            $data['travel_license_pic'] = get_content_cdnurl().$data['travel_license_pic'];
        }
        if(!empty($data['travel_license_pic2'])){
            $data['travel_license_pic2'] = get_content_cdnurl().$data['travel_license_pic2'];
        }
        if(!empty($data['travel_license_pic3'])){
            $data['travel_license_pic3'] = get_content_cdnurl().$data['travel_license_pic3'];
        }
        if(!empty($data['reg_cert_pic'])){
            $data['reg_cert_pic'] = get_content_cdnurl().$data['reg_cert_pic'];
        }
        if(!empty($data['reg_cert_pic2'])){
            $data['reg_cert_pic2'] = get_content_cdnurl().$data['reg_cert_pic2'];
        }
        if(!empty($data['reg_cert_pic3'])){
            $data['reg_cert_pic3'] = get_content_cdnurl().$data['reg_cert_pic3'];
        }
        return $data;
    }
}
